package org.msn.client.support;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.msn.client.ClientBoot;
import org.msn.client.handler.ClientHandler;
import org.msn.codec.MsgpackDecoder;
import org.msn.codec.MsgpackEncoder;

import java.util.concurrent.TimeUnit;

@Slf4j
public class DefaultClientBoot implements ClientBoot {
    @Override
    public void run(String ip, Integer port) throws InterruptedException {
        run(ip, port, new ClientHandler());
    }

    @Override
    public void run(String ip, Integer port, ChannelHandler channelHandler) throws InterruptedException {
        doRun(ip, port, channelHandler);
    }

    public synchronized void doRun(String ip, Integer port, ChannelHandler channelHandler) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ClientChannelInitializer());

            log.info("客户端启动");

            ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            eventExecutors.shutdownGracefully();
        }
    }

    private static class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline()
//                    .addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS))
                    .addLast(new MsgpackEncoder())
                    .addLast(new MsgpackDecoder())
                    .addLast(new ClientHandler())
                    .addLast(new LoggingHandler(LogLevel.INFO));
        }
    }
}
